package com.quzhi.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quzhi.common.code.Code;
import com.quzhi.common.Result;
import com.quzhi.sys.dto.OrderDto;
import com.quzhi.sys.entity.Order;
import com.quzhi.sys.entity.OrderSerialNumber;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.mapper.OrderMapper;
import com.quzhi.sys.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Xibing
 * @since 2024-06-29
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private OrderSerialNumberServiceImpl serialNumberService;

    @Autowired
    private OrderLogServiceImpl orderLogService;

    @Autowired
    private UserServiceImpl userService;

    // 添加订单
    @Override
    public Result<?> addOrder(Order order) {


        // 设置默认状态,未标记
        order.setOrderStatus(Code.WEI_BIAO_JI);
        // 设置扣款状态
        order.setDebitStatus(Code.WEI_KOU_KUAN);
        // 设置库存状态
        order.setStockStatus(Code.WEI_JIAN_KU_CUN);
        // 设置地址状态
        order.setAddressStatus(Code.ZHENG_CHANG);

        // 设置下单日期
        order.setOrderDate(LocalDateTime.now());

        // 更具起租期和天数计算结束的时间
        if (order.getStartTime() != null && order.getDuration() != null) {
            order.setEndTime(order.getStartTime().plusDays(order.getDuration() - 1));
        }


        // 更具发货时间计算时效
        if (order.getDeliveryDate() != null && order.getStartTime() != null) {
            if (order.getDeliveryDate().isBefore(order.getStartTime())) {
                // 计算两天的之间的时间
                long daysBetween = ChronoUnit.DAYS.between(order.getDeliveryDate(), order.getStartTime());
                order.setAgeing((int) daysBetween);
            }
        }


        // 设置创建时间
        order.setCreateTime(LocalDateTime.now());
        // 设置更新时间
        order.setUpdateTime(LocalDateTime.now());

        this.baseMapper.insert(order);

        return Result.success("添加订单成功");
    }

    @Override
    public void updateOrderById(Order order) {
        this.baseMapper.updateOrderById(order);
    }

    // 更具ID批量更新订单状态
    public Result<?> updateOrderStatusByIds(List<String> ids, String statusCode, String token) {
        User userinfoForBack = userService.getUserinfoForBack(token);

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        List<Order> orders = this.baseMapper.selectList(wrapper);


        int index = 0;
        for (String id : ids) {
            for (Order order : orders) {
                if (id.equals(order.getId())) {

                    order.setOrderStatus(statusCode);
                    order.setUpdateTime(LocalDateTime.now());

                    if (statusCode.equals(Code.DAI_FA_HUO)) {
                        if (order.getAddressStatus().equals(Code.DI_ZHI_XU_HES_SHI)) {
                            return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "该订单地址状态异常");
                        }
                        if (order.getDebitStatus().equals(Code.WEI_KOU_KUAN)) {
                            return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "该订单未扣款");
                        }
                        if (order.getStockStatus().equals(Code.WEI_JIAN_KU_CUN)) {
                            return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "该订单未减库存");
                        }
                        if (order.getStockStatus().equals(Code.MEI_YOU_KU_CUN)) {
                            return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "该订单没有库存");
                        }

                    }

                    if (statusCode.equals(Code.YI_FA_HUO)) {
                        if (order.getTrackingNumber() == null) {
                            return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "未输入发出单号");
                        }

                        // 检测序列号是否出库
                        LambdaQueryWrapper<OrderSerialNumber> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(OrderSerialNumber::getOrderId, order.getId());
                        List<OrderSerialNumber> list = serialNumberService.list(lambdaQueryWrapper);
                        for (OrderSerialNumber orderSerialNumber : list) {
                            if (orderSerialNumber.getStatus().equals(Code.DAI_CHU_KU)) {
                                return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "序列号待出库");
                            }
                        }

                    }
                    if (statusCode.equals(Code.YI_JI_HUI)) {
                        if (order.getReceiptNumber() == null) {
                            return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "未输入寄回单号");
                        }
                    }


                    // 如果发货日在今天之后字不能批量更新状态为发货中
                    if (statusCode.equals(Code.FA_HUO_ZHONG)) {
                        if (order.getDeliveryDate() == null || order.getDeliveryDate().toLocalDate().isAfter(LocalDate.now())) {
                            index += 1;
                            continue;
                        }
                    }

                    // 添加日志
                    orderLogService.AddSystemLog(order.getId(), "批量更新订单状态-" + statusCode, userinfoForBack.getUsername());

                    this.baseMapper.updateById(order);

                }
            }
        }

        if (index > 0) {
            return Result.fail(Code.UPDATE_FAIL_CODE, "有" + index + "个订单发货日，晚于当前日期，如果需要发货，请手动添加到发货中");
        }

        return Result.success("更新成功");

    }

    @Override
    public void updateOrderStockStatusByIds(List<String> ids, String statusCode, String token) {
        // 获取订单
        for (String id : ids) {
            Order order = this.baseMapper.selectById(id);
            order.setStockStatus(statusCode);
            // 修改订单
            this.baseMapper.updateById(order);

            User userinfoForBack = userService.getUserinfoForBack(token);

            // 添加日志
            orderLogService.AddSystemLog(id, "批量修改订单库存状态：" + statusCode, userinfoForBack.getUsername());

        }
    }

    @Override
    public List<OrderDto> getOrderList(OrderDto order) {
        return this.baseMapper.getOrdersByPage(order);
    }

    @Override
    public Integer getTotal(String orderStatus) {
        return this.baseMapper.getTotal(orderStatus);
    }

}
